package com.yx;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

import androidx.appcompat.app.AppCompatActivity;

import com.yx.serial.R;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;

public class MainActivity2 extends AppCompatActivity {
    EditText editText;
    /**
     * 通过执行cat命令读取节点值
     * @param path 节点路径
     * @return 节点中的字符串值，读取失败返回null
     */
    public static String readSysFsByRuntime(String path) {
        Process process = null;
        BufferedReader reader = null;
        String line = null;

        try {
            // 执行 "cat <路径>" 命令
            process = Runtime.getRuntime().exec("cat " + path);
            reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            line = reader.readLine();

            // 等待命令执行完成，并检查返回值
            int exitCode = process.waitFor();
            if (exitCode != 0) {
                Log.e("SysFsUtil", "命令执行失败，退出码: " + exitCode);
                line = null;
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
            Log.e("SysFsUtil", "通过Runtime读取节点失败: " + e.getMessage());
        } finally {
            // 手动关闭资源
            if (reader != null) {
                try { reader.close(); } catch (IOException e) { e.printStackTrace(); }
            }
            if (process != null) {
                process.destroy();
            }
        }
        return line;
    }
    /**
     * 读取系统节点值
     * @param path 节点路径，例如 "/sys/class/leds/led-red/brightness"
     * @return 节点中的字符串值，读取失败返回null
     */
    public static String readSysFsFile(String path) {
        String line = null;
        // 使用 try-with-resources 自动关闭资源，更安全
        try (BufferedReader reader = new BufferedReader(new FileReader(path))) {
            line = reader.readLine();
        } catch (IOException e) {
            e.printStackTrace();
            Log.e("SysFsUtil", "读取节点失败: " + path + ", 错误信息: " + e.getMessage());
        }
        return line; // 注意：如果节点内容有多行，此方法只返回第一行
    }
    private String getTem(){
        Process process = null;
        DataOutputStream dataOutputStream = null;

        DataInputStream dataInputStream = null;

        try {
            process = Runtime.getRuntime().exec("su");
            dataOutputStream = new DataOutputStream(process.getOutputStream());
            dataOutputStream.writeBytes( "chmod 0666 /sys/devices/platform/soc/soc:ap-ahb/22250000.i2c/i2c-1/1-007f/trs55d_data\n");
            dataOutputStream.writeBytes("exit\n");
            dataOutputStream.flush();
            process.waitFor();

            dataInputStream = new DataInputStream(process.getInputStream());
            int available = dataInputStream.available();
            if(available > 0){
                byte[] by = new byte[available];
                dataInputStream.read(by);
                String result = new String(by);
                Log.d("TAG", "ping: "+result);
                Log.i("ping", result);
                return result;
            }

            dataInputStream.close();
        } catch (Exception e) {
            //Log.e("adb", "shell exec fail ", e);
        } finally {
            try {
                if (dataOutputStream != null) {
                    dataOutputStream.close();
                }

                if (process != null) {
                    process.destroy();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return "获取失败";
    }
    public String readFileWithRoot(String filePath) {
        try {
            Process process = Runtime.getRuntime().exec("su");
            DataOutputStream os = new DataOutputStream(process.getOutputStream());
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));

            os.writeBytes("cat " + filePath + "\n");
            os.writeBytes("exit\n");
            os.flush();

            StringBuilder result = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                result.append(line);
            }

            process.waitFor();
            return result.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return "Error: " + e.getMessage();
        }
    }
    public String execSuCmd(String command) {
        StringBuilder msg = new StringBuilder();
        try {
            Log.d("TAG", "command:" + command);
            Process process = Runtime.getRuntime().exec("su");
            OutputStream out= process.getOutputStream();
            out.write(command.getBytes());
            out.flush();
            BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));

            String line;
            while ((line = input.readLine()) != null) {
                msg.append(line);
            }
            process.getOutputStream().close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return msg.toString();
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity2_main);
        editText =findViewById(R.id.editText);
        getTem();
        findViewById(R.id.getTem).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                editText.setText(readSysFsFile("/sys/devices/platform/soc/soc:ap-ahb/22250000.i2c/i2c-1/1-007f/trs55d_data"));
            }
        });
    }
}